package com.example.aigc_education.integration.response.workflows.v1;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

@Data
public class CozeGenFlashCResponse implements Serializable {

    @JsonProperty("content_type")
    private Integer content_type;

    @JsonDeserialize(using = CardDataListDeserializer.class)
    private List<CardData> data;

    @JsonProperty("original_result")
    private Object original_result;

    @JsonProperty("type_for_model")
    private Integer type_for_model;

    @Data
    public static class CardData implements Serializable{
        @JsonProperty("card_question")
        private String cardQuestion;
        @JsonProperty("card_answer")
        private String cardAnswer;
        private String interpretation;
    }

    public static class CardDataListDeserializer extends JsonDeserializer<List<CardData>> {
        @Override
        public List<CardData> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            ObjectMapper mapper = (ObjectMapper) p.getCodec();
            JsonNode node = p.readValueAsTree();
            if (node.isArray()) {
                return mapper.readValue(node.traverse(), mapper.getTypeFactory().constructCollectionType(List.class, CardData.class));
            } else if (node.isTextual()) {
                String jsonString = node.asText();
                return mapper.readValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, CardData.class));
            }
            throw new JsonProcessingException("Unexpected JSON format for CardData list") {};
        }
    }
}
